<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input :placeholder="$t('table.title')" v-model="listQuery.title" style="width: 200px;" class="filter-item"
                @keyup.enter.native="handleFilter"/>
      <el-select v-model="listQuery.state" :placeholder="$t('table.importance')" clearable style="width: 130px"
                 class="filter-item">
        <el-option v-for="(item,index) in importanceOptions " :key="item" :label="item" :value="index"/>
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="getKnowList">{{
        $t('table.search') }}
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"
                 @click="handleDownload">{{ $t('table.export') }}
      </el-button>

    </div>

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;">
<!--      @sort-change="sortChange">-->
      //序号
      <el-table-column :label="$t('table.id')" prop="id" sortable="custom" align="center" width="120px">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.date')" width="140px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.creationTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>

      //标题
      <el-table-column :label="$t('table.title')" width="90px">
        <template slot-scope="scope">
          <span>{{ scope.row.title }}</span>
        </template>
      </el-table-column>

      //内容
      <el-table-column :label="$t('table.content')" width="=150px">
        <template slot-scope="scope">
          <span>{{ scope.row.content }}</span>
        </template>
      </el-table-column>



      //状态
            <el-table-column :label="$t('table.status')" class-name="status-col" width="100px">
              <template slot-scope="scope">
                <el-tag :type="scope.row.state | statusFilter">{{ scope.row.state === 0 ? "待审核":"审核通过"}}</el-tag>
              </template>
            </el-table-column>
      //查看人数
      <el-table-column :label="$t('table.views')" width="80px">
        <template slot-scope="scope">
          <span>{{ scope.row.views }}</span>
        </template>
      </el-table-column>



<!--      按钮开始-->
      <el-table-column :label="$t('table.actions')" align="center" width="230px" class-name="small-padding fixed-width">
        <template slot-scope="scope">
<!--          编辑按钮-->
<!--          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>-->
<!--          *******************************************-->
<!--          操作按钮位置-->
<!--          审核-->
            <el-button v-if="scope.row.state!==1 " size="mini" type= 'success'
                       @click="getKnowAudit(scope.row.id)">{{ $t('table.audit') }}
            </el-button>
<!--          查看-->
          <el-button v-else size="mini" type= 'draft'
                     @click="getKnowAudit1(scope.row.id)">{{ $t('table.passAudit') }}
          </el-button>

          <el-button v-if="scope.row.status!='deleted'" size="mini" type="danger"
                     @click="is_delete(scope.row.id)">{{ $t('table.delete') }}
          </el-button>

<!--          按钮结束-->
        </template>
      </el-table-column>
    </el-table>



    <!--    分页查询 修改-->
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getKnowList"/>



<!--    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-->
    <!--          弹出审核 显示小知识的详细信息框 开始-->

    <el-dialog :visible.sync="dialogTableVisible" title="小知识审核" @dragDialog="handleDrag" width="800px">
      <el-form ref="form"   label-width="90px" >
        <el-form-item label="小知识编号">
          <el-input v-model="auditKnow.auditList.id" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="标题">
          <el-input v-model="auditKnow.auditList.title" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="内容">
          <el-input type="textarea" v-model="auditKnow.auditList.content" :disabled="true" :rows="4"  ></el-input>
        </el-form-item>
        <el-form-item label="视频"></el-form-item>
        <el-form-item label="视频名称">
          <el-input v-model="auditKnow.auditList.videoOriginalName" :disabled="true"></el-input>
        </el-form-item>
        <div class="video_wrap">
          <video-player class="vjs-custom-skin" ref="videoPlayer" :playsinline="true" :options="playerOptions"
                        @play="onPlay($event)"
                        @playing="onPlaying($event)"
                        @pause="onPause($event)"
                        @ended="onEnded($event)"
                        @waiting="onWaiting($event)"
                        @loadeddata="onLoadeddata($event)"
                        @timeupdate="onTimeupdate($event)"
                        @canplay="onCanplay($event)"
                        @canplaythrough="onCanplaythrough($event)"
                        @statechanged="playerStateChanged($event)"
                        @ready="playerReadied" />
        </div>
        <br>
        <el-form-item label="图片">
        </el-form-item>
        <div class="demo-image__lazy"  style="width: 410px; height: 310px;  margin-left: 140px"  >
          <el-container style="height: 300px">
            <el-main>
              <img  v-for="url in urls" :key="url" :src="url" lazy  width="390px" height="300px"  ></img>
            </el-main>
          </el-container>>
        </div>
        <br>
        <el-form-item label="发布人">
          <el-input v-model="auditKnow.auditList.nickname" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="发布时间">
          <el-col :span="11">
            <el-date-picker type="date" placeholder="选择日期" v-model="auditKnow.auditList.creationTime" style="width: 100%;" :disabled="true"></el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="状态">
          <el-input v-model="auditKnow.auditList.state === 0 ? '待审核': '审核通过' "  :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="未通过原因">
          <el-input type="textarea" v-model="auditKnow.auditList.notpassReason" :rows="4"  ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updateState(auditKnow.auditList.id)" >通过</el-button>
          <el-button>驳回</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

<!--    显示小知识的详细信息框  结束-->
<!--+++++++++++++++++++++++++++++++++++++++++++++++++++++-->



    <!--          弹出 显示小知识的详细信息框 开始-->

    <el-dialog :visible.sync="dialogTableVisible1" title="小知识查看" @dragDialog="handleDrag" width="800px">
      <el-form ref="form"   label-width="90px" >
        <el-form-item label="小知识编号">
          <el-input v-model="auditKnow.auditList.id" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="标题">
          <el-input v-model="auditKnow.auditList.title" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="内容">
          <el-input type="textarea" v-model="auditKnow.auditList.content" :disabled="true" :rows="4"  ></el-input>
        </el-form-item>
        <div v-show="auditKnow.auditList.videoSourceId== ''? false : true" >
        <el-form-item label="视频"></el-form-item>
        <el-form-item label="视频名称">
          <el-input v-model="auditKnow.auditList.videoOriginalName" :disabled="true"></el-input>
        </el-form-item>
        <div class="video_wrap">
          <video-player class="vjs-custom-skin" ref="videoPlayer" :playsinline="true" :options="playerOptions"
                        @play="onPlay($event)"
                        @playing="onPlaying($event)"
                        @pause="onPause($event)"
                        @ended="onEnded($event)"
                        @waiting="onWaiting($event)"
                        @loadeddata="onLoadeddata($event)"
                        @timeupdate="onTimeupdate($event)"
                        @canplay="onCanplay($event)"
                        @canplaythrough="onCanplaythrough($event)"
                        @statechanged="playerStateChanged($event)"
                        @ready="playerReadied" />
        </div>
        <br>
        </div>

        <div v-show="auditKnow.auditList.image== ''? false : true">
        <el-form-item label="图片">
        </el-form-item>
        <div class="demo-image__lazy"  style="width: 410px; height: 310px;  margin-left: 140px"  >
          <el-container style="height: 300px">
            <el-main>
              <img  v-for="url in urls" :key="url" :src="url" lazy  width="390px" height="300px"  ></img>
            </el-main>
          </el-container>>
        </div>
        </div>

        <br>
        <el-form-item label="发布人">
          <el-input v-model="auditKnow.auditList.nickname" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="发布时间">
          <el-col :span="11">
            <el-date-picker type="date" placeholder="选择日期" v-model="auditKnow.auditList.creationTime" style="width: 100%;" :disabled="true"></el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="状态">
          <el-input v-model="auditKnow.auditList.state === 0 ? '待审核': '审核通过' "  :disabled="true"></el-input>
        </el-form-item>
      </el-form>
    </el-dialog>

<!--  查看小信息-->
  </div>

</template>

<script>
  // import { fetchList, fetchPv, createArticle, updateArticle } from '@/api/article'
  import waves from '@/directive/waves' // Waves directive
  // import { parseTime } from '@/utils'
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
  // 引用 know.js文件
  import { getKonwledgeListPage, auditKnowById ,updateKnowState , deleteKnowByid } from '@/api/kno'

  //视频组件内引用
  import { videoPlayer } from 'vue-video-player'
  import 'video.js/dist/video-js.css'
  // import 'vue-video-player/src/custom-theme.css'

  import elDragDialog from '@/directive/el-dragDialog'
  const calendarTypeOptions = [
    {key: 'CN', display_name: 'China'},
    {key: 'US', display_name: 'USA'},
    {key: 'JP', display_name: 'Japan'},
    {key: 'EU', display_name: 'Eurozone'}
  ]

  // arr to obj ,such as { CN : "China", US : "USA" }
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  export default {
    name: 'ComplexTable',
    components: {Pagination},
    directives: {waves},
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger',
          0: 'danger',
          1: 'success'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      }
    },
    data() {
      return {
        dialogTableVisible: false,  //设置弹出框显示为false
        dialogTableVisible1: false,  //设置弹出框1显示为false
        tableKey: 0,
        list: null, //查询之后接口返回集合
        total: 0,
        listLoading: true,
        importanceOptions :['待审核','审核通过'] ,
        listQuery: {
          page: 1,
          limit: 10,  //每页记录数
          state: undefined,
          title: undefined,
          type: undefined,
          sort: '+id'
        },

        //用于显示审核小知识信息的表单,没用
        form: {
          name: '',
          region: '',
          date1: '',
          date2: '',
          delivery: false,
          type: [],
          resource: '',
          desc: ''
        },

        auditKnow: {
          auditList: {},  //获取审核数据接口返回集合
          id: ''   //用于查询时传id值
        },

        //用于视频播放
        playerOptions: {
          controls: true,  // 是否显示控制栏
          playbackRates: [0.5, 1.0, 1.5, 2.0], // 播放速度
          autoplay: false, // 如果为true,浏览器准备好时开始回放
          muted: false,    // 默认情况下将会消除任何音频。
          loop: false,     // 是否视频一结束就重新开始。
          preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
          language: 'zh-CN',
          aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
          fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
          sources: [{
            type: "video/mp4",
            src: ''
          }],
          poster: '', // 封面地址
          width: document.documentElement.clientWidth,
          notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
          controlBar: {
            timeDivider: true,           // 当前时间和持续时间的分隔符
            durationDisplay: true,       // 显示持续时间
            remainingTimeDisplay: false, // 是否显示剩余时间功能
            fullscreenToggle: true       // 是否显示全屏按钮
          }
        },
        playtimes: 5,     // 视频观看起点  (视频将从5s处开始播放)
        currentTime: 0,   // 当前播放进度
        duration: 0,      // 总时长


        //用于图片显示
        urls: [
          'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg',
          'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg',
          'https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg',
          'https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg',
          'https://fuss10.elemecdn.com/d/e6/c4d93a3805b3ce3f323f7974e6f78jpeg.jpeg',
          'https://fuss10.elemecdn.com/3/28/bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg',
          'https://fuss10.elemecdn.com/2/11/6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg'
        ],



        calendarTypeOptions,
        sortOptions: [{label: 'ID Ascending', key: '+id'}, {label: 'ID Descending', key: '-id'}],
        statusOptions: ['published', 'draft', 'deleted'],
        showReviewer: false,
        temp: {
          id: undefined,



          title: '',

        },

        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: 'Edit',
          create: 'Create'
        },
        dialogPvVisible: false,
        pvData: [],
        rules: {
          type: [{required: true, message: 'type is required', trigger: 'change'}],
          timestamp: [{type: 'date', required: true, message: 'timestamp is required', trigger: 'change'}],
          title: [{required: true, message: 'title is required', trigger: 'blur'}]
        },
        downloadLoading: false
      }

    },
    watch: {
      playtimes(val, oldVal) {
        this.playerReadied(this.$refs.videoPlayer.player, val);
      }
    },
    computed: {
      // 挂载视频组件（非必须）不写这一步也可以实现播放，添加这个是为了自定义按钮使用
      player() {
        return this.$refs.videoPlayer.player  // 自定义播放
      }
    },
    created() {
      // this.getList()
      this.getKnowList()

    },
    methods: {

      //做到了分页查询
      getKnowList() {
        this.listLoading = true
        getKonwledgeListPage(this.listQuery).then(response => {
          this.list = response.data.extend.rows
          this.total = response.data.extend.total

          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false
          },  1*1500)
        })
      },

      //根据id查询小知识内容,用于小知识审核
      getKnowAudit(id){
        this.auditKnow.id=id
        auditKnowById(this.auditKnow.id).then(response =>{
         console.log(response.data.extend.getknowByid)
          this.auditKnow.auditList=response.data.extend.getknowByid
          //动态获取后台视频地址
          this.playerOptions.sources[0].src = this.auditKnow.auditList.videoSourceId;
        })
        this.dialogTableVisible = true
      },

      //根据id查询小知识内容
      getKnowAudit1(id){
        this.auditKnow.id=id
        auditKnowById(this.auditKnow.id).then(response =>{
          console.log(response.data.extend.getknowByid)
          this.auditKnow.auditList=response.data.extend.getknowByid
          //动态获取后台视频地址
          this.playerOptions.sources[0].src = this.auditKnow.auditList.videoSourceId;
        })
        this.dialogTableVisible1 = true
      },

      //根据id修改小知识状态，用于小知识审核
      updateState(id){
        updateKnowState(id).then(response =>{
            this.$message.success(response.data.msg)
            this.getKnowList()
            this.dialogTableVisible = false
        })
      },

      //根据id删除小知识，用于删除小知识
      deleteState(id){

        deleteKnowByid(id).then(response=>{
          this.$message.success(response.data.msg)
          this.getKnowList()
        })
      },

      //修改状态
        handleModifyStatus(row, status) {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          row.status = status
        },

      //删除提示框
      is_delete(id) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteState(id);
          this.$message({

            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      //用来取消弹出框
      handleDrag() {
        this.$refs.select.blur()
      },



      //用于播放视频的方法
      // 当文件就绪可以开始播放时
      onCanplay(player) {
        this.duration = Math.floor(player.cache_.duration);// 总时长
      },
      // 当媒介数据已加载时
      onLoadeddata(player) {
        player.currentTime(this.playtimes); // 指定时间播放
      },
      // 当播放位置改变时（比如快进到媒介中一个不同的位置时）
      onTimeupdate(player) {
        this.currentTime = Math.ceil(player.cache_.currentTime);// 当前播放时长
      },
      // 播放回调
      onPlay(player) {},
      // 已开始播放回调
      onPlaying(player) {},
      // 暂停回调
      onPause(player) {},
      // 视频播完回调
      onEnded(player) {},
      // 当视频播放完毕已停止播放，再次点击播放时触发
      onWaiting(player) {},
      // 当媒介能够无需因缓冲而停止即可播放至结尾时
      onCanplaythrough(player) {},
      // 播放状态改变回调
      playerStateChanged(CurrentState) {},
      // 将侦听器绑定到组件的就绪状态。与事件监听器的不同之处在于，如果ready事件已经发生，它将立即触发该函数。。
      playerReadied(player) { },




      //   getList() {
      //     this.listLoading = true
      //     fetchList(this.listQuery).then(response => {
      //       this.list = response.data.items
      //       this.total = response.data.total
      //
      //       // Just to simulate the time of the request
      //       setTimeout(() => {
      //         this.listLoading = false
      //       }, 1.5 * 1000)
      //     })
      //   },
      //   handleFilter() {
      //     this.listQuery.page = 1
      //     this.getList()
      //   },
      //   handleModifyStatus(row, status) {
      //     this.$message({
      //       message: '操作成功',
      //       type: 'success'
      //     })
      //     row.status = status
      //   },
      //   sortChange(data) {
      //     const { prop, order } = data
      //     if (prop === 'id') {
      //       this.sortByID(order)
      //     }
      //   },
      //   sortByID(order) {
      //     if (order === 'ascending') {
      //       this.listQuery.sort = '+id'
      //     } else {
      //       this.listQuery.sort = '-id'
      //     }
      //     this.handleFilter()
      //   },
      //   resetTemp() {
      //     this.temp = {
      //       id: undefined,
      //       importance: 1,
      //       remark: '',
      //       timestamp: new Date(),
      //       title: '',
      //       status: 'published',
      //       type: ''
      //     }
      //   },
      //   handleCreate() {
      //     this.resetTemp()
      //     this.dialogStatus = 'create'
      //     this.dialogFormVisible = true
      //     this.$nextTick(() => {
      //       this.$refs['dataForm'].clearValidate()
      //     })
      //   },
      //   createData() {
      //     this.$refs['dataForm'].validate((valid) => {
      //       if (valid) {
      //         this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
      //         this.temp.author = 'vue-element-admin'
      //         createArticle(this.temp).then(() => {
      //           this.list.unshift(this.temp)
      //           this.dialogFormVisible = false
      //           this.$notify({
      //             title: '成功',
      //             message: '创建成功',
      //             type: 'success',
      //             duration: 2000
      //           })
      //         })
      //       }
      //     })
      //   },
      //   handleUpdate(row) {
      //     this.temp = Object.assign({}, row) // copy obj
      //     this.temp.timestamp = new Date(this.temp.timestamp)
      //     this.dialogStatus = 'update'
      //     this.dialogFormVisible = true
      //     this.$nextTick(() => {
      //       this.$refs['dataForm'].clearValidate()
      //     })
      //   },
      //   updateData() {
      //     this.$refs['dataForm'].validate((valid) => {
      //       if (valid) {
      //         const tempData = Object.assign({}, this.temp)
      //         tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
      //         updateArticle(tempData).then(() => {
      //           for (const v of this.list) {
      //             if (v.id === this.temp.id) {
      //               const index = this.list.indexOf(v)
      //               this.list.splice(index, 1, this.temp)
      //               break
      //             }
      //           }
      //           this.dialogFormVisible = false
      //           this.$notify({
      //             title: '成功',
      //             message: '更新成功',
      //             type: 'success',
      //             duration: 2000
      //           })
      //         })
      //       }
      //     })
      //   },
      //   handleDelete(row) {
      //     this.$notify({
      //       title: '成功',
      //       message: '删除成功',
      //       type: 'success',
      //       duration: 2000
      //     })
      //     const index = this.list.indexOf(row)
      //     this.list.splice(index, 1)
      //   },
      //   handleFetchPv(pv) {
      //     fetchPv(pv).then(response => {
      //       this.pvData = response.data.pvData
      //       this.dialogPvVisible = true
      //     })
      //   },
        handleDownload() {
          this.downloadLoading = true
          import('@/vendor/Export2Excel').then(excel => {
            const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
            const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
            const data = this.formatJson(filterVal, this.list)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: 'table-list'
            })
            this.downloadLoading = false
          })
        },
        formatJson(filterVal, jsonData) {
          return jsonData.map(v => filterVal.map(j => {
            if (j === 'timestamp') {
              return parseTime(v[j])
            } else {
              return v[j]
            }
          }))
        }
    }
  }
</script>
